package com.example.onepeak.androiddemo.common;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Justin.Shi on 2017/4/20.
 */

public abstract class SimpleAdapter<T> extends RecyclerView.Adapter<SimpleAdapter.ViewHolder> {

    private List<T> dataSets = new ArrayList<>();
    private int layoutId;

    private Context mContext;

    public SimpleAdapter(Context context, int layoutId) {
        mContext = context;
        this.layoutId = layoutId;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // create a new view
        View v = LayoutInflater.from(parent.getContext()).inflate(layoutId, null,false);
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        OnBindView(holder,dataSets.get(position),position);
    }

    @Override
    public int getItemCount() {
        return dataSets.size();
    }

    public void setDataSets(List<T> data) {
        dataSets.clear();
        addDataSets(data);
    }

    public void addDataSets(List<T> data) {
        dataSets.addAll(data);
        notifyDataSetChanged();
    }

    public void clearData() {
        dataSets.clear();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        private View mView;

        public ViewHolder(View itemView) {
            super(itemView);
            mView = itemView;
        }

        public View findViewById(int resId) {
            return mView.findViewById(resId);
        }
    }

    protected abstract void OnBindView(ViewHolder holder,T item, int position);
}
